package com.glsc.ngateway.platform.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.dto.PageDataResult;
import com.glsc.ngateway.common.api.common.enums.Constant;
import com.glsc.ngateway.common.api.common.enums.DictConstant;
import com.glsc.ngateway.common.api.common.enums.PlatformConstant;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.flowable.dto.*;
import com.glsc.ngateway.common.api.flowable.dto.param.ParamCreateDto;
import com.glsc.ngateway.common.api.flowable.dto.param.ParamDoTaskDto;
import com.glsc.ngateway.common.api.flowable.dto.param.ParamRollbackDto;
import com.glsc.ngateway.common.api.flowable.dto.task.config.ProcessEditConfigDto;
import com.glsc.ngateway.common.api.flowable.feign.IFeignFlowableService;
import com.glsc.ngateway.common.api.flowable.resp.*;
import com.glsc.ngateway.common.api.ldap.dto.LdapEhrEmpDto;
import com.glsc.ngateway.common.api.ldap.feign.IFeignLdapService;
import com.glsc.ngateway.common.api.ldap.resp.AppEhrResponse;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.base.converter.platform.FlowFormEventImproveConverter;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.flow.FlowFormEventDetailImprove;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.flow.FlowFormEventImprove;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.FlowFormEventDetailImproveRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.FlowFormEventImproveRepo;
import com.glsc.ngateway.platform.aspect.UserCache;
import com.glsc.ngateway.platform.service.itflow.config.ProcessEditConfigService;
import com.glsc.ngateway.platform.utils.JsonTool;
import com.glsc.ngateway.platform.utils.SpringUtil;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import javax.validation.constraints.NotBlank;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhouzp
 * @date 2022/12/8
 * 事件整改流程服务类，
 */
@Service
public class EventImproveService {

    Logger logger = LoggerFactory.getLogger(EventImproveService.class);

    @Resource
    private FlowFormEventImproveRepo flowFormEventImproveRepo;


    @Resource
    @Qualifier("transactionManagerMysql")
    private PlatformTransactionManager transactionManager;

    @Resource
    private UserCache userCache;

    @Resource
    private IFeignFlowableService feignFlowableService;

    @Resource
    private FlowCommonService flowCommonService;

    @Resource
    private ProcessEditConfigService processEditConfigService;

    @Resource
    private FlowFormEventDetailImproveRepo flowFormEventDetailImproveRepo;

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private MailService mailService;

    @Resource
    private IFeignLdapService feignEhrService;

    @Resource
    private UserService userService;


    /**
     * 保存事件整改流程表单
     *
     * @param formEventImproveForm
     * @return
     */
    public FlowFormEventImprove saveOrUpdateForm(FlowFormEventImproveDto formEventImproveForm) {
        return flowFormEventImproveRepo.save(Objects.requireNonNull(FlowFormEventImproveConverter.dto2Do(formEventImproveForm)));
    }

    /**
     * 根据processId获取事件整改流程表单
     *
     * @param processId 流程iD
     * @return
     */
    public FlowFormEventImproveDto findFormByProcessId(String processId) {
        return FlowFormEventImproveConverter.do2Dto(flowFormEventImproveRepo.findByProcessId(processId));
    }


    /**
     * 创建流程
     *
     * @param eventImproveTaskDto 流程创建发起对象
     * @return
     */
    public FlowDoTaskRespDto createFlow(EventImproveTaskDto eventImproveTaskDto, String operatorStart) {
        if (ObjectUtil.isNull(eventImproveTaskDto)
                || ObjectUtil.isNull(eventImproveTaskDto.getFlowableFormData())
                || StrUtil.isEmpty(operatorStart)) {
            throw PlatformException.errorWithOutMail("流程创建必填要素不能为空");
        }

        PlatformUserDto createUser = userCache.get(operatorStart);

        //【流程节点】，发起时动态指定节点处理人，
        Map<String, String> taskAssignee = this.initTaskUserGroup(operatorStart, eventImproveTaskDto.getFlowableFormData().getImprovePersonList());
        //【流程节点变量】
        Map<String, String> conditionalVariable = new HashMap<>();

        TransactionStatus status = null;
        FlowDoTaskRespDto createFlowResponse = null;
        FlowFormEventImproveDto flowableForm = eventImproveTaskDto.getFlowableFormData();
        try {
            // 事务定义
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            // 每次都开启一个新事务
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            // 获取事务状态
            status = transactionManager.getTransaction(def);

            //2.表单内容（发起流程，表单内容为辅助）
            FlowStartupFormDto formDto = new FlowStartupFormDto();
            formDto.setTitle(flowableForm.getProcessTitle());
            formDto.setComment("xx");//发起备注
            formDto.setCreatorId(createUser.getUserid());
            formDto.setCreatorName(createUser.getUsername());


            ParamCreateDto paramCreateDto = new ParamCreateDto();
            paramCreateDto.setSysid(PlatformConstant.SYS_ID_GATEWAY);
            paramCreateDto.setProcessDefinitionKey(PlatformConstant.FLOW_KEY_EVENT_IMPROVE);
            paramCreateDto.setUserid(operatorStart);//【重要！】这字段标识发起人！！！
            paramCreateDto.setContent(JSONObject.toJSON(formDto).toString());//纯粹为了flowable创建content需要一个JSON表单数据
            paramCreateDto.setTaskAssignee(taskAssignee);//各节点处理人
            paramCreateDto.setConditionalVariable(conditionalVariable);//控制流程节点变量
            if (eventImproveTaskDto.getCommentDto() != null) {
                paramCreateDto.setCreateComment(eventImproveTaskDto.getCommentDto().getFullMessage());
            } else {
                paramCreateDto.setCreateComment("系统自动创建");
            }


            createFlowResponse = new FlowDoTaskRespDto();
            //4.创建flowable流程
            FlowableResponse<ResponseCreateDto> createFlowableFlowResponse = feignFlowableService.create(paramCreateDto);
            if (createFlowableFlowResponse.getStatus() == 0) {
                createFlowResponse.setProcessId(createFlowableFlowResponse.getData().getProcessId());
                logger.info("流程关联，{}", createFlowResponse);
            } else {
                String errMsg = String.format("流程创建失败，{%s}，错误码={%s}-，原因：{%s}",
                        flowableForm.getProcessTitle()
                        , createFlowableFlowResponse.getStatus(), createFlowableFlowResponse.getMsg());
                logger.error(errMsg);
                throw PlatformException.error(errMsg);
            }


            //流程表单个性化要素保存（设置关联的流程）
            flowableForm.setProcessId(createFlowResponse.getProcessId());
            //保存申请人部门信息
            PlatformUserDto userCreater = userService.getUsrUrls(flowableForm.getFlowCreateOperatorAccount());
            flowableForm.setFlowCreatorDepartment(userCreater.getDepartment());
            FlowFormEventImprove flowableFormData = this.saveOrUpdateForm(flowableForm);

            //TODO 保存附件


            //提交事务
            transactionManager.commit(status);
        } catch (Exception e) {
            logger.error("异常，", e);

            String errMsg = "产品终止流程创建出现异常，回滚当前事务，原因:" + e.getMessage();
            if (status != null) {
                logger.error(errMsg);
                transactionManager.rollback(status);
            }
            throw PlatformException.error(errMsg);
        }

        return createFlowResponse;
    }

    private Map<String, String> initTaskUserGroup(String operatorStart, String improvePersonList) {
        //流程节点，发起时动态指定节点处理人，
        Map<String, String> taskAssignee = new HashMap<>();

        //TODO 需要查找具体的人员
        taskAssignee.put("improvePersonGroup", improvePersonList);//流程发起人
        taskAssignee.put("eventManageGroup", improvePersonList);//张文，需要配置角色

        return taskAssignee;
    }


    /**
     * 保存节点数据，但是不提交任务
     */
    public FlowDoTaskRespDto saveFormData(EventImproveTaskDto EventImproveTaskDto, String operatorStart) {
        if (ObjectUtil.isNull(EventImproveTaskDto)
                || ObjectUtil.isNull(EventImproveTaskDto.getFlowableFormData())
                || StrUtil.isEmpty(operatorStart)) {
            throw PlatformException.error("流程保存必填要素不能为空");
        }//TODO检查其它必填要素

        FlowDoTaskRespDto respDto = null;
        if (StrUtil.isNotEmpty(EventImproveTaskDto.getTaskId())) {//TODO 正式上线时，需要把taskId必传给打开
            respDto = flowCommonService.validCheckTaskBeforeSaveFormOrAuditTask(EventImproveTaskDto.getTaskId());
        } else {
            respDto = new FlowDoTaskRespDto();
        }

        FlowFormEventImproveDto flowableFormData = EventImproveTaskDto.getFlowableFormData();
        if (StrUtil.isNotEmpty(respDto.getProcessId())) {
            flowableFormData.setProcessId(respDto.getProcessId());
        }
        this.saveOrUpdateForm(EventImproveTaskDto.getFlowableFormData());

        return respDto;
    }


    /**
     * 审核通过
     */
    public FlowDoTaskRespDto taskAuditPass(EventImproveTaskDto taskDto, String operatorAccount) {

        //【1.任务合法性数据】
        FlowDoTaskRespDto respDto = flowCommonService.validCheckTaskBeforeSaveFormOrAuditTask(taskDto.getTaskId());
        //根据查询出的节点类型赋值
        taskDto.setTaskDefinitionKey(respDto.getTaskDefinitionKey());

        //流程注入变量更新
        Map<String, String> taskAssignee = new HashMap<>();
        Map<String, String> conditionalVariable = new HashMap<>();

        //TODO 节点个性化处理
        if (PlatformConstant.FLOW_EVENT_IMPROVE_NODE_BEGIN_TASK.equals(taskDto.getTaskDefinitionKey())) {//


        } else if (PlatformConstant.FLOW_EVENT_IMPROVE_NODE_FINISH_TASK.equals(taskDto.getTaskDefinitionKey())) {//
            //标记关闭（因为事件负责人也不对非自己的整改措施负责，所以整改负责人确认后即可关闭）
            taskDto.getFlowableFormData().setIsClose(1);

        } else if (PlatformConstant.FLOW_EVENT_IMPROVE_NODE_CONFIRM_TASK.equals(taskDto.getTaskDefinitionKey())) {//
            //标记关闭（此节点预留给历史数据使用，暂时不关闭）
            taskDto.getFlowableFormData().setIsClose(1);

        }


        //审核事务通过
        TransactionStatus status = null;
        try {
            // 事务定义
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            // 每次都开启一个新事务
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            // 获取事务状态
            status = transactionManager.getTransaction(def);

            //保存表单数据
            FlowDoTaskRespDto saveRespDto = this.saveFormData(taskDto, operatorAccount);
            if (saveRespDto == null) {
                throw PlatformException.error("保存表单数据失败");
            }


            //审核流程通过，组织表单内容、审核注入变量、评论等
            ParamDoTaskDto paramDotaskDto = new ParamDoTaskDto();
            paramDotaskDto.setSysid(PlatformConstant.SYS_ID_GATEWAY);
            paramDotaskDto.setTaskId(taskDto.getTaskId());
            paramDotaskDto.setComment(flowCommonService.initCommentDto(taskDto.getCommentDto()));
            paramDotaskDto.setTitle("");
            paramDotaskDto.setContent(JsonTool.objectToJson(paramDotaskDto));//flowable网关保存每次审批的全量数据
            paramDotaskDto.setTaskAssignee(taskAssignee);
            paramDotaskDto.setConditionalVariable(conditionalVariable);
            paramDotaskDto.setComment(taskDto.getCommentDto());


            //调用网关审核，注意前面表单的保存与这里审批通过，事物可能不一致，暂时不予处理这种不一致的情况
            FlowableResponse<ResponseMsgDto> flowableResponse = flowCommonService.taskAuditPass(paramDotaskDto);
            if (0 == flowableResponse.getStatus()) {
                //提交事务
                transactionManager.commit(status);

                return respDto;
            } else {
                String errMsg = "流程审核失败，错误码" + flowableResponse.getStatus() + "，原因：" + flowableResponse.getMsg() + "，详情：" + flowableResponse.getData();
                logger.error(errMsg);
                throw PlatformException.error(errMsg);
            }
        } catch (Exception e) {
            if (status != null) {
                logger.error("流程终止出现异常，回滚当前事务");
                transactionManager.rollback(status);
            } else {
                logger.error("流程终止出现异常，transaction def status is null");
            }
            throw e;
        }
    }


    /**
     * 审核驳回
     */
    public FlowDoTaskRespDto taskAuditReject(EventImproveTaskDto taskDto, String operatorStart) {

        //【1.任务合法性数据】
        FlowDoTaskRespDto respDto = flowCommonService.validCheckTaskBeforeSaveFormOrAuditTask(taskDto.getTaskId());


        //【2.公共处理】检查文件必传性，zzp  TODO

        //【3.获取任务审核前的流程信息】
        ResponseSituationDto beforeAuditFlowInfo = flowCommonService.getProcessInfo(respDto.getProcessId());
        //END OF【公共处理】查询任务基础信息

        //各节点，驳回时，业务逻辑特殊处理

        ParamRollbackDto flowableTaskDto = new ParamRollbackDto();
        flowableTaskDto.setSysid(PlatformConstant.SYS_ID_GATEWAY);
        flowableTaskDto.setTaskId(taskDto.getTaskId());
        flowableTaskDto.setComment(flowCommonService.initCommentDto(taskDto.getCommentDto()).getFullMessage());
        flowableTaskDto.setTitle("XXXXX");
        flowableTaskDto.setContent(JsonTool.objectToJson(flowableTaskDto));
        //驳回时，要求提供title、comment
        flowableTaskDto.setComment(taskDto.getCommentDto().getFullMessage());

        FlowableResponse<FlowDoTaskRespDto> flowableResponse = flowCommonService.taskAuditReject(flowableTaskDto);
        if (0 == flowableResponse.getStatus()) {
            //流程回退成功,后续处理 TODO

            return flowableResponse.getData();
        } else {
            throw PlatformException.error("流程退回失败");
        }
    }

    /**
     * 根据流程实例ID或者任务ID检索流程
     *
     * @param taskDto processId 流程ID
     * @param taskDto taskId 任务ID
     */
    public EventImproveTaskDto getWorkFlowFormByTaskId(EventImproveTaskDto taskDto) {
        if (taskDto == null || StrUtil.isEmpty(taskDto.getTaskId()) && StrUtil.isEmpty(taskDto.getProcessId())) {
            throw PlatformException.error("查询产品终止流程时，需要提供流程实例Id或者任务Id和流程节点标识");
        }

        EventImproveTaskDto respDto = new EventImproveTaskDto();


        ResponseSituationDto currentTaskInfo = null;
        if (StrUtil.isEmpty(taskDto.getTaskId())) {//流程结束或者抄送查看流程时，仅根据processId检索要素信息
            respDto.setProcessId(taskDto.getProcessId());
            respDto.setHandleProcessMode(PlatformConstant.FLOWABLE_HANDLE_MODE_VIEW);
            respDto.setCurrentTaskInfo(new ResponseSituationDto());//减轻前段判空处理
        } else {
            taskDto.setTaskId(StrUtil.trim(taskDto.getTaskId()));
            respDto.setHandleProcessMode(PlatformConstant.FLOWABLE_HANDLE_MODE_EDIT);
            FlowableResponse<ResponseSituationDto> flowableTaskInfoResponse = flowCommonService.getTaskInfo(taskDto.getTaskId()
                    , PlatformConstant.SYS_ID_GATEWAY);
            if (flowableTaskInfoResponse.getStatus() != 0) {
                throw PlatformException.error("流程引擎未查询到任务信息" + taskDto.getTaskId());
            } else {
                taskDto.setProcessId(flowableTaskInfoResponse.getData().getProcessId());//后续保存策略会用到processId
                currentTaskInfo = flowableTaskInfoResponse.getData();
                respDto.setCurrentTaskInfo(currentTaskInfo);//task 任务详情
                respDto.setProcessId(currentTaskInfo.getProcessId());
                respDto.setTaskId(currentTaskInfo.getCurrentTaskId());//具体任务方式查看，需要taskId/taskDefinitionKey
                respDto.setTaskDefinitionKey(currentTaskInfo.getCurrentTaskDefinitionKey());
                respDto.setProcessDefineKey(currentTaskInfo.getProcessDefineKey());

                //加载任务节点信息
                ProcessEditConfigDto editConfigDto = processEditConfigService.getProcessEditConfigDto(respDto.getProcessDefineKey(), respDto.getTaskDefinitionKey());
                respDto.setProcessEditConfigDto(editConfigDto);
            }
        }

        //查询表单数据
        FlowFormEventImproveDto flowFormEventImprove = this.findFormByProcessId(respDto.getProcessId());
        if (flowFormEventImprove == null) {
            throw PlatformException.error("未查询到关联的流程表单数据");
        }
        respDto.setFlowableFormData(flowFormEventImprove);


        return respDto;
    }

    public List<FlowFormEventDetailImprove> queryByImprovePersonListSon(List<String> improveAdminEmps) {
        Specification<FlowFormEventDetailImprove> specification = new Specification<FlowFormEventDetailImprove>() {
            @Override
            public Predicate toPredicate(Root<FlowFormEventDetailImprove> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                List<Predicate> list = Lists.newArrayList();
//                list.add(cb.equal(root.get("tenantId"), user.getTenantId()));
                List<Predicate> or = Lists.newArrayList();
                for (String id : improveAdminEmps) {
                    Expression<String> findInSetFun = cb.function("FIND_IN_SET", String.class, cb.literal(id), root.get("improvePersonList"));
                    //设置条件 只要返回值 >0 则说明该参数存在于目标字符串中
                    or.add(cb.notEqual(findInSetFun, "0"));
                }
                return cb.or(or.toArray(new Predicate[or.size()]));
            }
        };
        List<FlowFormEventDetailImprove> improveList = flowFormEventDetailImproveRepo.findAll(specification).stream().distinct().collect(Collectors.toList());
        return improveList;
    }

    //根据改善人员查询改善流程,避免数量太多堆栈溢出，手动限制数量
    public List<FlowFormEventDetailImprove> queryByImprovePersonList(List<String> improveAdminEmps) {
        int total = improveAdminEmps.size();
        int querySize = 2000;
        List<FlowFormEventDetailImprove> tmpDetailListAll = new ArrayList<>();
        for (int i = 0; i <= Integer.valueOf(total / querySize); i++) {
            List<String> tmpList = improveAdminEmps.subList(i*querySize,(i+1)*querySize > total ? total : (i+1)*querySize);
            List<FlowFormEventDetailImprove> tmpDetailList = queryByImprovePersonListSon(tmpList);
            tmpDetailListAll.addAll(tmpDetailList);
        }
        return tmpDetailListAll.stream().distinct().collect(Collectors.toList());
    }

    /**
     * 提醒改善流程
     *
     * @param o
     * @return
     */
    public String notifyEventImproveEnd(Object o) {
        //获取需要提醒的日期(0代表计划完成当天，负数代表提前多少天，正数代表往后多少天)
        String notifyDay = systemConfigService.findConfigValueByCode("EVENT_IMPROVE_NOTIFYDAY");
        if (StrUtil.isEmpty(notifyDay)) {
            notifyDay = "-3,0,7";
        }
        //构造出要提醒的日期
        List<String> notifyDayList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate currentDate = LocalDate.now();
        for (String day : notifyDay.split(",")) {
            LocalDate newDate = currentDate.plusDays(-Integer.valueOf(day));//加负号才能计算出提前和推后的天数
            String formattedDate = newDate.format(formatter);
            notifyDayList.add(formattedDate);
        }

        //找出指定未结束的改善流程
        List<FlowFormEventImprove> improveList = flowFormEventImproveRepo.findByIsCloseAndPlanDateIn(DictConstant.NO_CLOSE,notifyDayList);
        //往后需要提醒的间隔
        String notifyDayBetweenString = systemConfigService.findConfigValueByCode("EVENT_IMPROVE_NOTIFYDAY_BETWEEN");
        Integer notifyDayBetween = Integer.valueOf(notifyDayBetweenString);
        List<FlowFormEventImprove> improveListLeft = flowFormEventImproveRepo.findByIsClose(DictConstant.NO_CLOSE);
        improveListLeft = improveListLeft.stream().filter(e->{
            LocalDate localDate = LocalDate.parse(e.getPlanDate(), formatter);
            long daysBetween = ChronoUnit.DAYS.between(currentDate, localDate);
            //提醒间隔的倍数，且为之前的日期
            if (daysBetween % notifyDayBetween == 0 && daysBetween < 0){
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        //合并去重

        improveList.addAll(improveListLeft);
        improveList = improveList.stream().distinct().collect(Collectors.toList());

        if (CollectionUtil.isNotEmpty(improveList)){
            String mailTitle = "事件整改流程结束提醒";
            for (FlowFormEventImprove improve:improveList) {
                List<String> mailRecvList = new ArrayList<>();
                String mailTitleLink = "http://zy.glsc.com.cn/gateway/accidentMgr/improveAudit?flowProcessId="+improve.getProcessId();
                String accountStrings = improve.getImprovePersonList();
                for (String account : accountStrings.split(",")) {
                    AppEhrResponse<List<LdapEhrEmpDto>> respone = feignEhrService.getEmpsByAccounts(ImmutableList.of(account));
                    if (Objects.nonNull(respone) && respone.isSuccess() && CollectionUtil.isNotEmpty(respone.getData())) {
                        LdapEhrEmpDto userInfo = respone.getData().get(0);
                        if (SpringUtil.isTestingByActiveProfile()) {//测试环境，发给测试人员
                            mailRecvList.add("weizt@glsc.com.cn");
                            logger.info("实际发送人为：" +userInfo.getEmail());
                        } else {
                            mailRecvList.add(userInfo.getEmail());
                        }
                    }
                }
                StringBuilder mailContent = new StringBuilder("" +
                        "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您有事件整改流程[" + improve.getProcessTitle() + "]待处理，" +
                        "请点击上方标题链接，使用OA账号、密码登入国联技术服务平台进行处理。也可以进入流程管理-流程代办菜单，或查询事件管理-查询事件流程-流程类型选择事件整改查看相关记录。<br/>");
                //邮件发送
                if (CollectionUtils.isEmpty(mailRecvList)) {
                    logger.warn("未查找到保管人");
                    mailService.sendMailToAdmin(mailTitle, mailContent.toString());
                    mailService.sendMailToAdmin(mailTitle + "未查找到保管人", "未查找到保管人");
                } else {
                    mailRecvList = mailRecvList.stream().distinct().collect(Collectors.toList());
                    String send = systemConfigService.findConfigValueByCode(Constant.CONFIG_KEY_DIGITAL_KEY_SEND_MAIL);
                    if ("true".equals(send)) {
                        mailService.sendMail(mailRecvList.toArray(new String[mailRecvList.size()]), null, mailTitle, mailTitleLink, mailTitle, mailContent.toString(), null, Constant.MAIL_TYPE_COMMON_LINK);
                    } else {
                        logger.info("事件提醒邮件开关未打开，不发送邮件" + mailRecvList);
                    }
                }
            }
        }
        return "";
    }

    /**
     * 根据流程id，查找所有改善流程信息
     *
     * @param pageNo
     * @param pageSize
     * @param paramSearchDto
     * @param operatorStart
     * @return
     */
    public Page<ResponseSituationEventDto> findImproveProcessPage(Integer pageNo, Integer pageSize, FlowParamSearchDto paramSearchDto, String operatorStart) {
        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);
        if (StrUtil.isEmpty(paramSearchDto.getOrderByDirection())) {
            paramSearchDto.setOrderByDirection("DESC");
        }
        if (StrUtil.isEmpty(paramSearchDto.getOrderByField())) {
            paramSearchDto.setOrderByField("isClose");
        }
        Sort sort = Sort.by(Sort.Direction.fromString(paramSearchDto.getOrderByDirection()), paramSearchDto.getOrderByField());
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        Page<FlowFormEventImprove> result = flowFormEventImproveRepo.searchByParam(pageable, paramSearchDto);
        List<FlowFormEventImprove> content = result.getContent();
        List<ResponseSituationEventDto> process = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(content)) {
            for (FlowFormEventImprove flow : content) {
                FlowableResponse<ResponseSituationDto> processInfo = feignFlowableService.getProcessInfo(flow.getProcessId());
                ResponseSituationEventDto eventDto = new ResponseSituationEventDto();
                BeanUtil.copyProperties(processInfo.getData(), eventDto);
                eventDto.setIsClose(flow.getIsClose());
                process.add(eventDto);
            }
        }

        Page<ResponseSituationEventDto> resultPage = new PageImpl(process, pageable, result.getTotalElements());
        return resultPage;
    }

    public List<FlowFormEventImprove> findAllByFromEventProcessId(@NotBlank String processId) {
        return flowFormEventImproveRepo.findAllByFromEventProcessId(processId);
    }
}
